package com.yfuxdeer.youchat.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.yfuxdeer.youchat.dao.MessageDao;
import com.yfuxdeer.youchat.dao.impl.MessageDaoImpl;
import com.yfuxdeer.youchat.pojo.Message;
import com.yfuxdeer.youchat.pojo.MessageItem;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageService extends Service {

    private MessageDao messageDao = new MessageDaoImpl();
    private final String TAG = MessageService.class.getSimpleName();
    private Bundle bundle;
    private Bundle data;

    public enum METHOD {
        FIND_MESSAGE_ITEM,
        FIND_MESSAGE
    }

    public enum RESULT {
        SUCCESS, NETWORK_EXCEPTION
    }

    public void findMessageItems() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Map<String, MessageItem> messageItemMap = new HashMap<>(); // friend_id --> 消息列表项
                    String username = bundle.getString("username");
                    //查找所有发给我的消息
                    List<Message> sendToMeAll = messageDao.findSendToMeAll(username);
                    for (Message s : sendToMeAll) {
                        MessageItem message = messageDao.findLastMessage(username, s.getFrom());
                        MessageItem m = messageItemMap.get(s.getFrom());
                        if (m == null) {
                            messageItemMap.put(s.getFrom(), message);
                            continue;
                        }
                        Date ori = m.getTime();
                        Date ne = message.getTime();
                        if (ori.compareTo(ne) < 0) {
                            //说明之前的时间更早需要更新
                            messageItemMap.put(s.getFrom(), message);
                        }
                    }
                    //查询我发给别人的消息
                    List<Message> ISendTo = messageDao.findISendToAll(username);
                    for (Message s : ISendTo) {
                        MessageItem message = messageDao.findLastMessage(username, s.getTo());
                        MessageItem m = messageItemMap.get(s.getTo());
                        if (m == null) {
                            messageItemMap.put(s.getTo(), message);
                            continue;
                        }
                        Date ori = m.getTime();
                        Date ne = message.getTime();
                        if (ori.compareTo(ne) < 0) {
                            //说明之前的时间更早需要更新
                            messageItemMap.put(s.getTo(), message);
                        }
                    }
                    List<MessageItem> messageItemList = new ArrayList<>();
                    for (Map.Entry<String, MessageItem> entry : messageItemMap.entrySet()) {
                        messageItemList.add(entry.getValue());
                    }
                    data.putSerializable("messageItemList", (Serializable) messageItemList);
                    data.putSerializable("result", RESULT.SUCCESS);
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.findMessageItemReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    public void findAllMessageAboutAFriend() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String host_id = bundle.getString("host_id");
                    String friend_id = bundle.getString("friend_id");
                    List<Message> messages = messageDao.findAllMessageWithAFriend(host_id, friend_id);
                    data.putSerializable("messages", (Serializable) messages);
                    data.putSerializable("result", RESULT.SUCCESS);
                } catch (Exception e) {
                    data.putSerializable("result", RESULT.NETWORK_EXCEPTION);
                }
                Intent broadcast = new Intent("com.yfuxdeer.youchat.findMessageReceiver");
                broadcast.putExtras(data);
                sendBroadcast(broadcast);
            }
        }).start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: " + "接收到服务请求");
        bundle = intent.getExtras();
        data = new Bundle();
        METHOD method = (METHOD) bundle.getSerializable("method");
        switch (method) {
            case FIND_MESSAGE_ITEM:
                findMessageItems();
                break;
            case FIND_MESSAGE:
                findAllMessageAboutAFriend();
                break;
        }
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }
}
